/*
 * Copyright (C) 2012  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.remote.socket.internal;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import nemos.remote.rsa.message.IConnection;
import nemos.remote.rsa.message.IServer;
import nemos.remote.rsa.message.impl.ConnectionImpl;
import nemos.remote.socket.ISocketService;

import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.osgi.framework.BundleContext;

/**
 * SocketServiceImpl : The socket service implementation.
 * 
 * @author Romain DUBOIS
 */
@Service(ISocketService.class)
@Component
public class SocketServiceImpl implements ISocketService {

    /** The bundle context */
    private BundleContext mContext;

    /** The created connections */
    private final Collection<ConnectionImpl> mConnections;

    /**
     * Constructor.
     */
    public SocketServiceImpl() {
        super();

        mConnections = new ArrayList<ConnectionImpl>();
    }

    /**
     * Start the component.
     * 
     * @param pContext
     *            The bundle context
     */
    @Activate
    public void start(final BundleContext pContext) {
        mContext = pContext;
    }

    /**
     * Stop the component
     */
    @Deactivate
    public void stop() {
        for (final Iterator<ConnectionImpl> lIt = mConnections.iterator(); lIt.hasNext();) {
            final ConnectionImpl lConnection = lIt.next();
            if (lConnection.isActive()) {
                lConnection.stop();
            }
            lIt.remove();
        }
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.socket.ISocketService#createServer(int)
     */
    @Override
    public IServer createServer(final int pPort) throws IOException {
        return createServer(null, pPort);
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.socket.ISocketService#createServer(java.lang.String,
     *      int)
     */
    @Override
    public IServer createServer(final String pHostName, final int pPort) throws IOException {
        final SocketMessageServer lServer = new SocketMessageServer(pHostName, pPort);
        lServer.start(mContext);
        add(lServer.connect());
        return lServer;
    }

    /**
     * {@inheritDoc}
     * 
     * @see nemos.remote.socket.ISocketService#connectServer(java.lang.String,
     *      int)
     */
    @Override
    public IConnection connectServer(final String pHostName, final int pPort) throws IOException {
        // Connect to the server
        final Socket lSocket = new Socket(pHostName, pPort);

        // Wrap socket in a transport
        final SocketTransport lTransport = new SocketTransport(lSocket);

        // Then create a connection
        final ConnectionImpl lConnection = new ConnectionImpl(lTransport);
        lConnection.start(mContext);
        add(lConnection);
        return lConnection;
    }

    /**
     * Add a connection.
     * 
     * @param pConnection
     *            The connection to add
     */
    private void add(final ConnectionImpl pConnection) {
        for (final Iterator<ConnectionImpl> lIt = mConnections.iterator(); lIt.hasNext();) {
            final ConnectionImpl lConnection = lIt.next();
            if (!lConnection.isActive()) {
                lIt.remove();
            }
        }
        mConnections.add(pConnection);
    }
}
